#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:Summerday


import csv
import os

def getDataFromGDF(path):
	node_data = []
	edge_data = []
	isNode = True
	with open(path,mode='r',encoding="utf-8") as f:


		line = f.readline()
		while line:
			line = line.strip('\n')
			if line.startswith('N'):
				isNode = True
				node_headers = line[2:].split(',')
				print(node_headers)
				
			elif line.startswith('E'):
				isNode = False
				edge_headers = line[2:].split(',')
				print(edge_headers)

			else:
				if isNode:
					node_data.append(line.split(',')[:-1])
				else:
					edge_data.append(line.split(',')[:-1])
			line = f.readline()
	data = {
		'node_headers':node_headers,
		'node_data':node_data,
		'edge_data':edge_data,
		"edge_headers":edge_headers
	}
	return data
def write2csv(data):
	
	node_fileName = 'hzx/node.csv'
	edge_fileName = 'hzx/edge.csv'
	
	if os.path.exists(node_fileName):
		os.remove(node_fileName)
	
	# 写node
	with open(node_fileName,'w',encoding='utf-8',newline='') as f:
		csv_writer = csv.writer(f)
		# 头信息
		csv_writer.writerow(data["node_headers"])
		# 写入内容
		for i in data["node_data"]:
			csv_writer.writerow(i)
		
	if os.path.exists(edge_fileName):
		os.remove(edge_fileName)
	# edge
	with open(edge_fileName,'w',encoding='utf-8',newline='') as f:
		csv_writer = csv.writer(f)
		# 头信息
		csv_writer.writerow(data["edge_headers"])
		# 写入内容
		for i in data["edge_data"]:
			csv_writer.writerow(i)
			



d =  getDataFromGDF("D:\comp\hzxkin.txt")
write2csv(d)